/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.swirrel.installer;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

import java.awt.Component;
import java.lang.annotation.Annotation;
import javax.swing.DefaultListSelectionModel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionListener;

import org.swirrel.annotation.ValueChanged;
import org.swirrel.listener.SwirrelListSelectionListener;
import org.swirrel.util.MethodCall;

/**
 *
 * @author Gronau
 */
public class ListSelectionListenerInstaller
    extends AbstractListenerInstaller implements SwirrelListenerInstaller {

  public ListSelectionListenerInstaller() {
    super(Arrays.<Class<? extends Annotation>> asList(ValueChanged.class),
          Arrays.<Class<?>> asList(JList.class, JTable.class));
  }

  public boolean isListenerAlreadySet(Object obj) {
    ListSelectionListener[] listSelectionListeners = null;
    if (obj instanceof JTable) {
      ListSelectionModel model = ( (JTable) obj).getSelectionModel();
      listSelectionListeners = (model instanceof DefaultListSelectionModel)
          ? ( (DefaultListSelectionModel) model).getListSelectionListeners()
          : new ListSelectionListener[] {}; //no way to get the listeners
    }
    else {
      listSelectionListeners = ( (JList) obj).getListSelectionListeners();
    }
    for (ListSelectionListener lsl : listSelectionListeners) {
      if (lsl instanceof SwirrelListSelectionListener) {
        return true;
      }
    }
    return false;
  }

  public void registerListener(Field field, Component comp,
                               List<MethodCall> methodCalls) throws
      IllegalAccessException {
    Object obj = field.get(comp);
    ListSelectionListener lsl = new SwirrelListSelectionListener(methodCalls.get(0));
    if (obj instanceof JTable) {
      ( (JTable) obj).getSelectionModel().addListSelectionListener(lsl);
    }
    else {
      ( (JList) obj).addListSelectionListener(lsl);
    }
  }
}
